<template>
  <div class="buttonNodes">
    <el-button type="default" @click="$emit('generateExample')">
      {{ isExample ? '取消示例' : '示例' }}
    </el-button>
    <el-button type="primary" @click="$emit('generateConfig')">生成配置</el-button>
    <el-button v-if="configResult" style="margin-left: 10px" type="primary" @click="$emit('copyConfig')">
      复制配置
    </el-button>
    <el-button v-if="configResult" style="margin-left: 10px" type="success" @click="handlePush">
      推送
    </el-button>
  </div>
</template>

<script>
import { addOrRemoveDomain } from '@/api/request_server'
import { buildConfig } from '@/assets/data/configBuilder'

export default {
  name: 'FormActions',
  props: {
    isExample: {
      type: Boolean,
      default: false
    },
    configResult: {
      type: String,
      default: ''
    },
    host: {
      type: String
    },
    dirpath: {
      type: String,
      default: ''
    },
    templateName: {
      type: String
    }
  },
  methods: {
    async handlePush() {
      if (!this.$store.getters.apipermissions.addAd) {
        this.$message.warning('该操作无授权')
        return
      }
      console.log(this.host, this.configResult)
      if (!this.host || !this.configResult) {
        this.$message.warning('缺少推送必要信息')
        return
      }

      try {
        const messagetype = this.host.length > 10 ? 'success' : 'warning'
        await this.$confirm(
          `你确定为站点 <b>${this.host}</b><br>
                    ${this.templateName}
                    添加广告配置吗？`,
          '操作确认',
          {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: messagetype
          }
        )
        const defaultconfig = buildConfig({
          host: this.host,
          dirpath: this.dirpath,
          templateName: this.templateName
        })

        const data = {
          host: this.host,
          dirpath: this.dirpath,
          template: this.templateName,
          tasktag: 2,
          status: 0,
          defaultconfig: defaultconfig,
          config: this.configResult,
          operator: this.$store.getters.name
        }
        const res = await addOrRemoveDomain(data)
        if (res.code === 20000) {
          this.$message.success('推送请求已发送')
          this.$emit('pushSuccess', res)
        } else {
          this.$message.error('推送请求发送失败：' + (res.message || '未知错误'))
          this.$emit('pushFail', res)
        }
      } catch (err) {
        if (err === 'cancel') {
          this.$message.info('已取消推送')
          this.$emit('pushCancel')
        } else {
          this.$message.error('推送异常：' + (err.message || err))
          this.$emit('pushError', err)
        }
      }
    }
  }
}
</script>

<style scoped>
.buttonNodes {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
